package team.niit.filter;


import team.niit.bean.UserBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: HAPPY
 * @Project_name: student_select_course
 * @Package_name: team.niit.filter
 * @Date: 2021/12/13 19:32
 * @Description:
 */
public class PowerFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        // 放行静态资源请求和 默认主页、找回密码、登录请求、未登录提示页面
        if (uri.contains("js") || uri.contains("css") || uri.contains("png") || uri.contains("jpg")
                || uri.contains("gif") || uri.contains("svg")
                || "/student_select_course/".equals(uri)
                || "/student_select_course/retrieve_password.xhtml".equals(uri)
                || "/student_select_course/login.xhtml".equals(uri)
                || "/student_select_course/pages/error/login_first.xhtml".equals(uri)) {
            chain.doFilter(request, response);
            return;
        }

        UserBean user = (UserBean) req.getSession().getAttribute("user");
        // 如果没有登录，为空，如果登陆过但是登录失败了，user可能不为空，但是id为空
        if (user == null || user.getId() == null) {
            resp.sendRedirect("/student_select_course/pages/error/login_first.xhtml");
            return;
        }
    
        // 登录学生账号后访问管理员功能
        if (user.getId().length() > 6 && uri.contains("admin")) {
            resp.sendRedirect("/student_select_course/pages/error/insufficient_permissions.xhtml");
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
